package com.jxinternet.platform.services.handler;

import com.jxinternet.platform.services.entity.protobuf.SocketModelProtos;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * 解码器1
 * 解第一层
 */

public class CustomProtobufDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        // 标记，指向当前指针位置，读取数据时使用
        in.markReaderIndex();

        while (in.readableBytes() > 4) { // 如果可读长度小于包头长度，退出。

            // 获取包头中的body长度 长度为一个short类型2个byte字节
            byte low = in.readByte();
            byte high = in.readByte();
            short s0 = (short) (low & 0xff);
            short s1 = (short) (high & 0xff);
            s1 <<= 8;
            short length = (short) (s0 | s1);

            // 如果可读长度小于body长度，恢复读指针，退出。
            if (in.readableBytes() < length) {
                in.resetReaderIndex();
                return;
            }

            //多读2个字节
            in.readShort();

            //读取body
            ByteBuf bodyByteBuf = in.readBytes(length);

            byte[] array;
            int offset;

            int readableLen = bodyByteBuf.readableBytes();
            if (bodyByteBuf.hasArray()) {
                array = bodyByteBuf.array();
                offset = bodyByteBuf.arrayOffset() + bodyByteBuf.readerIndex();
            } else {
                array = new byte[readableLen];
                bodyByteBuf.getBytes(bodyByteBuf.readerIndex(), array, 0, readableLen);
                offset = 0;
            }

            //反序列化
            SocketModelProtos.SocketModelRequest socketModel = SocketModelProtos.SocketModelRequest.getDefaultInstance().getParserForType().parseFrom(array, offset, readableLen);
            out.add(socketModel);

        }
    }


}
